/**
 * IPC API 服务类
 * 负责与主进程通信
 */
class ApiService {
  constructor() {
    this.isAvailable = this.detectElectronEnvironment();
  }

  detectElectronEnvironment() {
    // 检测是否在 Electron 环境中
    const isElectron = !!(
      window.electronAPI && typeof window.electronAPI === "object"
    );
    console.log("[ApiService] Electron 环境检测:", {
      electronAPI: !!window.electronAPI,
      type: typeof window.electronAPI,
      executeClaudeHeadless: !!(
        window.electronAPI && window.electronAPI.executeClaudeHeadless
      ),
      isElectron,
    });
    return isElectron;
  }

  isElectron() {
    return this.isAvailable;
  }

  async checkClaudeCode() {
    if (!this.isElectron()) {
      // 浏览器环境模拟
      return { success: true, installed: false };
    }
    return await window.electronAPI.checkClaudeCode();
  }

  async getClaudeCodeInfo() {
    if (!this.isElectron()) {
      // 浏览器环境模拟
      return {
        success: true,
        info: { installed: false, shouldShowInstallPage: true },
      };
    }
    return await window.electronAPI.getClaudeCodeInfo();
  }

  async getClaudeCodeVersion() {
    if (!this.isElectron()) {
      // 浏览器环境模拟
      return {
        success: true,
        version: { success: false, error: "Browser environment" },
      };
    }
    return await window.electronAPI.getClaudeCodeVersion();
  }

  async testClaudeDetector() {
    if (!this.isElectron()) {
      // 浏览器环境模拟
      return {
        success: true,
        result: { installed: false, error: "Browser environment" },
      };
    }
    return await window.electronAPI.testClaudeDetector();
  }

  async installClaudeCode() {
    if (!this.isElectron()) {
      throw new Error("仅支持在 Electron 环境中运行");
    }
    return await window.electronAPI.installClaudeCode();
  }

  async validateApiKey(apiKey) {
    if (!this.isElectron()) {
      // 浏览器环境模拟验证
      return { success: true, valid: apiKey && apiKey.length > 10 };
    }
    return await window.electronAPI.validateApiKey(apiKey);
  }

  async executeTask(apiKey, task, model = "claude-3-sonnet-20240229") {
    if (!this.isElectron()) {
      // 浏览器环境模拟
      return {
        success: true,
        result: `模拟执行结果：${task}\n\n这是一个模拟的结果，实际使用需要 Electron 环境。`,
      };
    }
    return await window.electronAPI.executeTask({ apiKey, task, model });
  }

  async saveApiKey(apiKey) {
    if (!this.isElectron()) {
      // 浏览器环境保存到localStorage
      localStorage.setItem("apiKey", apiKey);
      return { success: true };
    }
    return await window.electronAPI.saveApiKey(apiKey);
  }

  async loadApiKey() {
    if (!this.isElectron()) {
      // 浏览器环境从localStorage读取
      const apiKey = localStorage.getItem("apiKey");
      return { success: true, apiKey };
    }
    return await window.electronAPI.loadApiKey();
  }

  async getTaskHistory(limit = 50) {
    if (!this.isElectron()) {
      return { success: true, history: [] };
    }
    return await window.electronAPI.getTaskHistory(limit);
  }

  async clearCache() {
    if (!this.isElectron()) {
      localStorage.clear();
      return { success: true };
    }
    return await window.electronAPI.clearCache();
  }

  async getAppInfo() {
    if (!this.isElectron()) {
      return {
        name: "CCloud AI Agent",
        version: "1.0.0",
        platform: "web",
      };
    }
    return await window.electronAPI.getAppInfo();
  }

  async executeClaudeHeadless(apiKey, task) {
    if (!this.isElectron()) {
      // 浏览器环境模拟
      return {
        success: true,
        output: `模拟无头模式结果：${task}\n\n这是一个模拟的结果，实际使用需要 Electron 环境。`,
        source: "simulated",
        exitCode: 0,
      };
    }
    return await window.electronAPI.executeClaudeHeadless({ apiKey, task });
  }

  async executeSystemClaude(apiKey, task) {
    if (!this.isElectron()) {
      return {
        success: true,
        output: `模拟系统 Claude 结果：${task}\n\n这是一个模拟的结果，实际使用需要 Electron 环境。`,
        source: "simulated",
        exitCode: 0,
      };
    }
    return await window.electronAPI.executeSystemClaude({ apiKey, task });
  }

  /**
   * 测试 API 连接（公共方法）
   * @param {string} apiKey - API Key
   * @param {string} provider - 模型厂商
   * @param {string} model - 模型名称
   * @param {number} timeout - 超时时间（毫秒），默认 15 秒
   * @returns {Object} 测试结果
   */
  async testApiConnection(apiKey, provider, model, timeout = 15000) {
    console.log('[ApiService] testApiConnection 开始');
    console.log('[ApiService] 参数:', {
      provider,
      model,
      apiKey: apiKey ? '***' + apiKey.slice(-4) : 'none',
      timeout: timeout / 1000 + '秒',
      isElectron: this.isElectron()
    });

    try {
      // 使用一个简单的测试任务
      const testTask = "Hello";

      // 创建超时 Promise
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => {
          console.warn('[ApiService] 测试超时，已等待', timeout / 1000, '秒');
          reject(new Error(`连接测试超时（${timeout / 1000}秒），请检查网络或配置`));
        }, timeout);
      });

      // 使用专门的测试连接 IPC，确保使用传入的 apiKey，而不是存储的配置
      console.log('[ApiService] 准备调用测试接口...');
      const apiCallPromise = this.isElectron() 
        ? window.electronAPI.invoke('claude:test-connection', { apiKey, task: testTask })
        : this.executeClaudeHeadless(apiKey, testTask);

      console.log('[ApiService] 等待测试结果...');
      // 使用 Promise.race 实现超时控制
      const result = await Promise.race([apiCallPromise, timeoutPromise]);

      console.log('[ApiService] 收到测试结果:', result);

      // executeClaudeHeadless 返回的结构是 { success, output, source, exitCode }
      // 错误信息在 output 字段中，不是 error 字段
      const response = {
        success: result.success,
        message: result.success 
          ? "连接成功" 
          : (result.output || result.error || "未知错误"),
        source: result.source
      };

      console.log('[ApiService] 返回结果:', response);
      return response;
    } catch (error) {
      console.error('[ApiService] testApiConnection 异常:', error);
      console.error('[ApiService] 错误详情:', {
        message: error.message,
        stack: error.stack
      });
      
      return {
        success: false,
        message: error.message,
        source: "timeout"
      };
    }
  }
}

// 创建全局API服务实例
const apiService = new ApiService();

// 导出到全局
window.apiService = apiService;
